import React from 'react';
import PropTypes from 'prop-types';
import { Balloon, PopConfirm, Dropdown, Button, Menu, Tag } from '@teamix/ui';
import { YunxiaoList, ButtonIcon, YunxiaoIcon } from '@alife/devops-ui';
import CreateCRModal from 'components/createCRModal/loadable';
import { PROJECT_WRITE_ROLES, PROJECT_ADMIN_ROLES } from 'utils/constants.js';
import AccessContainer from 'components/accessContainer';
import { access } from 'components/accessContainer/util';
import { navigate, Link, HrefLink } from 'utils/router';
import './index.scss';
import BuildsResultTag from 'components/buildsResultTag';
import Cover from 'atComponents/Cover';
import utils from 'utils';
import UpdateInfo from './updateInfo';
import track from 'utils/track';
import BranchCommitOrder from 'components/branchCommitOrder';
import intl from '../../../../../../../../locale';

const { pathResource } = window.FORCE;

export default class BranchList extends React.Component {
  static propTypes = {
    branchDataSource: PropTypes.arrayOf(PropTypes.object),
    projectInfo: PropTypes.object,
    lastMirrorSyncRecord: PropTypes.object,
  };

  state = {
    visible: false,
    submitting: false,
  };

  onDefaultBranchClick = () => {
    track({
      action: 'set_default_branch',
      page: 'Repo-Branches',
      type: '',
      control: '',
    });

    navigate(`/${pathResource.fullPath}/settings/branches`);
  };

  onCancel = () => {
    this.setState({
      visible: false,
    });
  };

  onConfirm = (name) => {
    if (this.state.submitting) return;
    this.setState({ submitting: true });
    this.props.deleteBranch(
      name,
      () => {
        this.setState({
          visible: false,
          submitting: false,
        });
      },
      () => {
        this.setState({ submitting: false });
      },
    );
  };

  onMoreClick = () => {
    const { visible } = this.state;
    this.setState({
      visible: !visible,
    });
  };

  render() {
    const { branchDataSource, projectInfo, lastMirrorSyncRecord } = this.props;
    const { role, isArchive } = pathResource;

    if (!branchDataSource) {
      return false;
    }

    const colorMap = {
      opened: 'green',
      reopened: 'green',
      accepted: 'green',
      merged: null,
      closed: 'red',
    };

    const iconMap = {
      opened: 'pull-request-line',
      reopened: 'pull-request-line',
      accepted: 'pull-request-line',
      merged: 'merge-line',
      closed: 'pull-request-closed-line',
    };

    const textMap = {
      opened: intl.get({
        id: 'code-assets.components.mrTitleInfo.Enabled',
        defaultMessage: '已开启',
      }),
      reopened: intl.get({
        id: 'code-assets.components.mrTitleInfo.Enabled',
        defaultMessage: '已开启',
      }),
      accepted: intl.get({
        id: 'code-assets.components.mrTitleInfo.Enabled',
        defaultMessage: '已开启',
      }),
      merged: intl.get({
        id: 'code-assets.components.mrTitleInfo.Merged',
        defaultMessage: '已合并',
      }),
      closed: intl.get({
        id: 'code-assets.components.mrTitleInfo.Disabled',
        defaultMessage: '已关闭',
      }),
    };

    let hasOpenStateMr = false;
    const { last_merge_request } = branchDataSource;
    if (
      last_merge_request !== null &&
      (last_merge_request.state === 'opened' || last_merge_request.state === 'accepted')
    ) {
      hasOpenStateMr = true;
    }

    const { isCrModalOpen } = this.state;
    const CrModalJsx = isCrModalOpen && (
      <CreateCRModal
        isModalOpen={isCrModalOpen}
        defaultSourceBranch={branchDataSource.name}
        title={
          branchDataSource.last_code_review
            ? branchDataSource.last_code_review.title
            : branchDataSource.commit.title
        }
        {...this.props}
        cannotChangeProject
        defaultProjectId={window.FORCE.pathResource.id}
        onCloseModal={() => {
          this.setState({
            isCrModalOpen: false,
          });
        }}
      />
    );

    let isMirrorSynchronizing = false;
    if (lastMirrorSyncRecord) {
      isMirrorSynchronizing = utils.isMirrorSynchronizing(lastMirrorSyncRecord.sync_status);
    }

    const dataSource = {
      cover: (
        <>
          {branchDataSource.protected ? (
            <>
              {access(PROJECT_ADMIN_ROLES, role) ? (
                <HrefLink
                  href={`/${pathResource.fullPath}/settings/branches`}
                  target="_blank"
                  rel="noreferrer"
                >
                  <Balloon.Tooltip
                    align="t"
                    trigger={
                      <Cover
                        type="icon"
                        icon={
                          <YunxiaoIcon
                            type="safe-line"
                            style={{ color: 'var(--color-success-5, #23b066)' }}
                          />
                        }
                      />
                    }
                  >
                    {intl.get({
                      id: 'code-assets.containers.branchListItem.ProtectionBranch',
                      defaultMessage: '保护分支',
                    })}
                  </Balloon.Tooltip>
                </HrefLink>
              ) : (
                <Balloon.Tooltip
                  align="t"
                  trigger={
                    <Cover
                      type="icon"
                      icon={
                        <YunxiaoIcon
                          type="safe-line"
                          style={{ color: 'var(--color-success-5, #23b066)' }}
                        />
                      }
                    />
                  }
                >
                  {intl.get({
                    id: 'code-assets.containers.branchListItem.ProtectionBranch',
                    defaultMessage: '保护分支',
                  })}
                </Balloon.Tooltip>
              )}
            </>
          ) : (
            <Cover
              type="icon"
              icon={<YunxiaoIcon type="branches-line" style={{ color: '#6e6e6e' }} />}
            />
          )}
        </>
      ),
      body: {
        title: [
          <span className="branch-card-item-title">
            <Balloon.Tooltip
              align="t"
              trigger={
                <Link
                  style={{ float: 'left' }}
                  to={`/${pathResource.fullPath}/tree/${utils.revisionEncodeURI(
                    branchDataSource.name,
                  )}`}
                  className="branch-item-title"
                >
                  {branchDataSource.name}
                </Link>
              }
            >
              {branchDataSource.name}
            </Balloon.Tooltip>

            {/* {branchDataSource.protected ? (
              <span style={{ marginLeft: 8 }}>
                {access(PROJECT_ADMIN_ROLES, role) ? (
                  <a href={`/${pathResource.fullPath}/settings/branches`} target="_blank" rel="noreferrer">
                    <Tag color="green">
                      {intl.get({
                        id: 'code-assets.containers.branchListItem.ProtectionBranch',
                        defaultMessage: '保护分支',
                      })}
                    </Tag>
                  </a>
                ) : (
                  <Tag color="green">
                    {intl.get({
                      id: 'code-assets.containers.branchListItem.ProtectionBranch',
                      defaultMessage: '保护分支',
                    })}
                  </Tag>
                )}
              </span>
            ) : null} */}
          </span>,
          <UpdateInfo branchDataSource={branchDataSource} />,
          <BuildsResultTag
            container={{
              target: 'commit', // 可选值为 commit 和 merge_request
              id: branchDataSource.commit.id, // commit 或 merge_request 的 id
            }}
            projectInfo={projectInfo}
          />,
        ],
      },

      right: {
        items:
          branchDataSource.name === pathResource.defaultBranch
            ? [
              <Tag className="default-branch-tag">
                {intl.get({
                    id: 'code-assets.containers.branchListItem.DefaultBranch',
                    defaultMessage: '默认分支',
                  })}
              </Tag>,
                isArchive === 'false' ? (
                  <span>
                    <AccessContainer neededRole={PROJECT_ADMIN_ROLES} role={role}>
                      <Button type="normal" onClick={this.onDefaultBranchClick}>
                        {intl.get({
                          id: 'code-assets.containers.branchListItem.ModifyTheDefaultBranch',
                          defaultMessage: '修改默认分支',
                        })}
                      </Button>
                    </AccessContainer>
                  </span>
                ) : null,
              ]
            : [
              <BranchCommitOrder
                info={branchDataSource}
                targetBranch={pathResource.defaultBranch}
              />,

              <>
                <div className="branch-mr">
                  <span>
                    {branchDataSource.last_merge_request ? (
                      <Balloon
                        trigger={
                          <span
                            onClick={() => {
                                track({
                                  action: 'goto_mr',
                                  page: 'Repo-Branches',
                                  type: '',
                                  control: '',
                                });
                              }}
                          >
                            <a
                              href={branchDataSource.last_merge_request.detail_url}
                              target="_blank"
                              rel="noreferrer"
                            >
                              <Tag
                                color={colorMap[branchDataSource.last_merge_request.state]}
                                size="medium"
                                className={'branch-mr-tag'}
                              >
                                <span>
                                  <YunxiaoIcon
                                    type={iconMap[branchDataSource.last_merge_request.state]}
                                  />{' '}
                                  {textMap[branchDataSource.last_merge_request.state]}
                                </span>
                              </Tag>
                            </a>
                          </span>
                          }
                        closable={false}
                        align="tl"
                      >
                        <div className="branch-mr-balloon">
                          <div className="branch-mr-balloon-title">
                            {branchDataSource.last_merge_request.title}
                          </div>
                          <span className="branch-mr-balloon-branch-container">
                            <span className="branch-mr-balloon-branch">
                              {last_merge_request.source_branch}
                            </span>{' '}
                            <YunxiaoIcon
                              type="arrow-right-line"
                              size="small"
                              className="branch-mr-balloon-branch-icon"
                            />{' '}
                            <span className="branch-mr-balloon-branch">
                              {last_merge_request.target_branch}
                            </span>
                          </span>
                        </div>
                      </Balloon>
                      ) : (
                        <React.Fragment>
                          {access(PROJECT_WRITE_ROLES, role) ? (
                            <React.Fragment>
                              {isArchive === 'false' ? (
                                <React.Fragment>
                                  <Button
                                    type="normal"
                                    onClick={() => {
                                      track({
                                        action: 'new_mr',
                                        page: 'Repo-Branches',
                                        type: '',
                                        control: '',
                                      });

                                      this.setState({
                                        isCrModalOpen: true,
                                      });
                                    }}
                                  >
                                    {intl.get({
                                      id: 'code-assets.containers.branchListItem.CreateMergeRequest',
                                      defaultMessage: '新建合并请求',
                                    })}
                                  </Button>
                                  {CrModalJsx}
                                </React.Fragment>
                              ) : null}
                            </React.Fragment>
                          ) : (
                            <React.Fragment>
                              <Balloon.Tooltip
                                trigger={
                                  <Button type="normal" disabled>
                                    {intl.get({
                                      id: 'code-assets.containers.branchListItem.CreateMergeRequest',
                                      defaultMessage: '新建合并请求',
                                    })}
                                  </Button>
                                }
                                align="t"
                                text={intl.get({
                                  id: 'code-assets.containers.branchListItem.YouAreNotAuthorizedTo',
                                  defaultMessage: '无权限新建合并请求，请联系管理员申请对应的权限',
                                })}
                              />
                            </React.Fragment>
                          )}
                        </React.Fragment>
                      )}
                  </span>
                </div>
                {access(PROJECT_WRITE_ROLES, role) &&
                    branchDataSource.last_merge_request?.state === 'merged' &&
                    CrModalJsx}
                <Dropdown
                  trigger={<ButtonIcon name="more-line" onClick={this.onMoreClick} />}
                  triggerType="click"
                  visible={this.state.visible}
                  onVisibleChange={(visible, type) => {
                      if (type === 'docClick') {
                        this.setState({
                          visible,
                        });
                      }
                    }}
                >
                  <Menu>
                    {access(PROJECT_WRITE_ROLES, role) &&
                      branchDataSource.last_merge_request?.state === 'merged' ? (
                        <Menu.Item
                          onClick={() => {
                            track({
                              action: 'new_mr',
                              page: 'Repo-Branches',
                              type: '',
                              control: '',
                            });

                            this.setState({
                              isCrModalOpen: true,
                            });
                          }}
                        >
                          新建合并请求
                        </Menu.Item>
                      ) : null}
                    <Menu.Item
                      onClick={() => {
                          track({
                            action: 'campare_branch',
                            page: 'Repo-Branches',
                            type: '',
                            control: '',
                          });

                          this.setState({
                            visible: false,
                          });

                          navigate(
                            `/${pathResource.fullPath}/compare?from=${encodeURIComponent(
                              pathResource.defaultBranch,
                            )}&to=${encodeURIComponent(branchDataSource.name)}&tab=branches`,
                          );
                        }}
                    >
                      {intl.get({
                          id: 'code-assets.containers.branchListItem.Comparison',
                          defaultMessage: '比较',
                        })}
                    </Menu.Item>
                    {isArchive === 'false' && isMirrorSynchronizing && (
                    <Menu.Item disabled className="branch-delete-menu">
                      <Balloon.Tooltip
                        trigger={
                          <span className="branch-delete-menu-text">
                            {intl.get({
                                  id: 'code-assets.containers.branchListItem.Delete',
                                  defaultMessage: '删除',
                                })}
                          </span>
                            }
                        align="t"
                        text={intl.get({
                              id: 'code-assets.containers.branchListItem.TheRepositoryIsBeingSynchronized',
                              defaultMessage: '仓库同步中，暂不支持操作，请稍后再试',
                            })}
                      />
                    </Menu.Item>
                      )}

                    {isArchive === 'false' &&
                        PROJECT_WRITE_ROLES.includes(role) &&
                        !branchDataSource.protected &&
                        !hasOpenStateMr &&
                        !isMirrorSynchronizing && (
                          <Menu.Item className="branch-delete-menu">
                            <PopConfirm
                              triggerType="click"
                              align="t"
                              type="warning"
                              title={intl.get({
                                id: 'code-assets.containers.branchListItem.ConfirmDeletion',
                                defaultMessage: '确认删除',
                              })}
                              needAdjust
                              content={
                                branchDataSource.ahead === 0
                                  ? intl.get({
                                      id: 'code-assets.containers.branchListItem.TheCurrentBranchHasBeen',
                                      defaultMessage: '当前分支已合并至master',
                                    })
                                  : intl.get({
                                      id: 'code-assets.containers.branchListItem.TheCurrentBranchHasNot',
                                      defaultMessage: '当前分支尚未合并至master',
                                    })
                              }
                              onConfirm={() => {
                                this.onConfirm(branchDataSource.name);
                              }}
                              confirmProps={{ loading: this.state.submitting }}
                              onCancel={this.onCancel}
                              popupProps={{ loading: this.state.submitting }}
                              trigger={
                                <span className="branch-delete-menu-text">
                                  {intl.get({
                                    id: 'code-assets.containers.branchListItem.Delete',
                                    defaultMessage: '删除',
                                  })}
                                </span>
                              }
                            />
                          </Menu.Item>
                        )}

                    {isArchive === 'false' &&
                        !(PROJECT_WRITE_ROLES.includes(role) && !branchDataSource.protected) &&
                        !hasOpenStateMr &&
                        !isMirrorSynchronizing && (
                          <Menu.Item disabled className="branch-delete-menu">
                            <Balloon.Tooltip
                              trigger={
                                <span className="branch-delete-menu-text">
                                  {intl.get({
                                    id: 'code-assets.containers.branchListItem.Delete',
                                    defaultMessage: '删除',
                                  })}
                                </span>
                              }
                              align="t"
                              text={
                                PROJECT_WRITE_ROLES.includes(role) && branchDataSource.protected
                                  ? intl.get({
                                      id: 'code-assets.containers.branchListItem.TheProtectedBranchCannotBe',
                                      defaultMessage: '保护分支不允许删除',
                                    })
                                  : intl.get({
                                      id: 'code-assets.containers.branchListItem.YouAreNotAuthorizedTo.1',
                                      defaultMessage:
                                        '无权限进行删除操作，请联系管理员申请对应的权限',
                                    })
                              }
                            />
                          </Menu.Item>
                        )}

                    {isArchive === 'false' && hasOpenStateMr && !isMirrorSynchronizing && (
                    <Menu.Item disabled className="branch-delete-menu">
                      <Balloon.Tooltip
                        trigger={
                          <span className="branch-delete-menu-text">
                            {intl.get({
                                  id: 'code-assets.containers.branchListItem.Delete',
                                  defaultMessage: '删除',
                                })}
                          </span>
                            }
                        align="t"
                        text={intl.get({
                              id: 'code-assets.containers.branchListItem.AnEnabledMergeRequestCannot',
                              defaultMessage: '存在开启的合并请求，无法删除',
                            })}
                      />
                    </Menu.Item>
                      )}
                  </Menu>
                </Dropdown>
              </>,
              ],
      },
    };

    return (
      <YunxiaoList.Item
        className="branch-item"
        cover={dataSource.cover}
        title={dataSource.body.title[0]}
        description={dataSource.body.title[1]}
        extra={
          <>
            <YunxiaoList.Item.Actions width="144px" align="left">
              {dataSource.body.title[2]}
            </YunxiaoList.Item.Actions>
            <YunxiaoList.Item.Actions width="180px" align="center">
              {dataSource.right.items[0]}
            </YunxiaoList.Item.Actions>
            <YunxiaoList.Item.Actions width="170px" align="right">
              {dataSource.right.items[1]}
            </YunxiaoList.Item.Actions>
          </>
        }
      />
    );
  }
}
